import { defineStore } from 'pinia'
import {getCookie, setCookie, deleteCookie} from '@/util/dkmk'
import { getUserInfoByUser, UserInfor } from '@/api/login'
import {InstitutionalData, getInstitutionalData} from '@/api/baseSetting/institutionalData'
interface UserState{
  token:string|null
  //用户信息 TODO
  userInfor:UserInfor|null //用户信息 包括基础信息和权限信息
  userOrgInfor:InstitutionalData|null  //用户机构资料信息
}

const userStore = defineStore('userStore', {
  state:():UserState => {
    return {
      token:getCookie('Token'),
      userInfor:null,
      userOrgInfor:null
    }
  },
  actions:{
    //刷新Token
    refreshToken(token:string) {
      console.log('dayingtonken', token)

      setCookie('Token', token)
      this.token = token
    },
    //删除Token
    deleteToken() {
      deleteCookie('Token')
      this.token = null
    },
    //刷新用户信息
    refreshUserInfo(info:UserInfor) {
      this.userInfor = info
    },
    //获取用户信息 refresh是否强制刷新
    getUseInfor(refresh?:boolean) {
      return new Promise((resolve, reject) => {
        if (this.userInfor && !refresh) {
          resolve(this.userInfor)
        } else {
          getUserInfoByUser().then((res) => {
            const {data} = res.data
            this.userInfor = data
            resolve(data)
          }).catch((error) => {
            reject(error)
          })
        }
      })
    },
    //刷新用户机构信息
    refreshUserOrgInfo(info:InstitutionalData) {
      this.userOrgInfor = info
    },
    //获取用户机构资料 refresh是否强制刷新
    getUseOrgInfor(refresh?:boolean) {
      return new Promise((resolve, reject) => {
        if (this.userOrgInfor && !refresh) {
          resolve(this.userOrgInfor)
        } else {
          getInstitutionalData().then((res) => {
            const {data} = res.data
            this.userOrgInfor = data
            resolve(data)
          }).catch((error) => {
            reject(error)
          })
        }
      })
    }
  }
})

export default {
  setup() {
    const store = userStore()
    //重置信息
    const reset = () => {
      store.token = null
      store.userInfor = null
      store.userOrgInfor = null
    }
    return {store, reset}
  }
}